/*
 *    This program is free software; you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation; either version 2 of the License, or
 *    (at your option) any later version.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    2013 year
 *    Author: Esipenko Aleksey (Alexorleon)
 *    E-Mail: alexorleon@gmail.com
 */
#include "createnewplacement.h"
#include "ui_createnewplacement.h"

createNewPlacement::createNewPlacement(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::createNewPlacement)
{
    ui->setupUi(this);

    createConnections();
    requestdatabase();

    ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);
    ui->buttonBox->button(QDialogButtonBox::Cancel)->setText(tr("Отмена"));
    // учитываем только цифры
    QRegExp rx("(|\"|/|\\.|[0-9]){30}");
    ui->lnEditPhone->setValidator(new QRegExpValidator(rx, this));

    ui->tableView->horizontalHeader()->setResizeMode(QHeaderView::Stretch);
}

createNewPlacement::~createNewPlacement()
{
    delete ui;
}

void createNewPlacement::createConnections(){

    connect(ui->btnDelete,SIGNAL(clicked()),this,SLOT(slot_deleteItem()));
    connect(ui->btnAdd,SIGNAL(clicked()),this,SLOT(slot_addItem()));
    connect(ui->lnEditPlacement,SIGNAL(textChanged(QString)),this,SLOT(slot_editPlace()));
    connect(ui->lnEditPhone,SIGNAL(textChanged(QString)),this,SLOT(slot_editPhone()));
    connect(ui->lnEditEmail,SIGNAL(textChanged(QString)),this,SLOT(slot_editEmail()));
}

void createNewPlacement::requestdatabase(){

    // заносим таблицу в tableview
    model.setTable("placements");
    model.select();
    ui->tableView->setModel(&model);
    ui->tableView->hideColumn(0);
    model.setHeaderData(1, Qt::Horizontal, tr("Место размещения"));
    model.setHeaderData(2, Qt::Horizontal, tr("Телефон"));
    model.setHeaderData(3, Qt::Horizontal, tr("Email"));
    ui->tableView->show();
}

void createNewPlacement::slot_deleteItem(){

    if(ui->tableView->currentIndex().isValid()){

        // запоминаем все выделенные строки
        QItemSelection selection(ui->tableView->selectionModel()->selection());

        if( !selection.isEmpty()){

            QList<int> rows;
            foreach(const QModelIndex &index, selection.indexes() ){
                rows.append(index.row());
            }
            qSort(rows);

            int prev = -1;
            // удаляем все выделенные строки
            for( int i = rows.count() - 1; i >= 0; i -= 1 ) {
                int current = rows[i];
                if(current != prev){
                    model.removeRows(current, 1);
                    prev = current;
                }
            }
            ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(true);
        }
    }
}

void createNewPlacement::slot_addItem(){

    // извлекаем место размещения
    QString strPlace = ui->lnEditPlacement->text();
    // извлекаем телефон
    QString strPhone = ui->lnEditPhone->text();
    // извлекаем email
    QString strEmail = ui->lnEditEmail->text();
    bool isEdit=true;
    if(strPlace.isEmpty()){
        ui->lnEditPlacement->setStyleSheet("background-color: rgb(255, 81, 81);");
        isEdit=false;
    }
    if(strPhone.isEmpty()){
        ui->lnEditPhone->setStyleSheet("background-color: rgb(255, 81, 81);");
        isEdit=false;
    }
    if(strEmail.isEmpty()){
        ui->lnEditEmail->setStyleSheet("background-color: rgb(255, 81, 81);");
        isEdit=false;
    }
    if(isEdit){
        // добавляем место размещения
        QSqlQuery query;
        query.prepare("INSERT INTO placements (placement, phone, email) VALUES (?,?,?)");
        query.addBindValue(strPlace);
        query.addBindValue(strPhone);
        query.addBindValue(strEmail);
        query.exec();

        requestdatabase();
        ui->lnEditPlacement->clear();
        ui->lnEditPhone->clear();
        ui->lnEditEmail->clear();

        ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(true);
    }
}

void createNewPlacement::slot_editPlace(){

    // убираем цвет
    if(ui->lnEditPlacement->text().count() == 1){
        ui->lnEditPlacement->setStyleSheet("");
    }
}

void createNewPlacement::slot_editPhone(){

    if(ui->lnEditPhone->text().count() == 1){
        ui->lnEditPhone->setStyleSheet("");
    }
}

void createNewPlacement::slot_editEmail(){

    if(ui->lnEditEmail->text().count() == 1){
        ui->lnEditEmail->setStyleSheet("");
    }
}
